<template>
  <t-row :gutter="[16, 16]">
    <t-col :flex="3">
      <div class="user-left-greeting">
        <div>
          Hi，{{ name }}
          <span class="regular"></span>
        </div>
        <!-- <img src="@/assets/assets-tencent-logo.png" class="logo" /> -->
      </div>

      <card class="user-info-list" size="small" title="个人信息">
        <template #option>
          <t-button theme="default" shape="square" variant="text" v-show="!edit" @click="clickEdit">
            <t-icon name="edit" size="18" />
          </t-button>
          <t-button theme="default" shape="square" variant="text" v-show="edit" @click="confrimEdit">
            <t-icon name="check" size="18" />
          </t-button>
        </template>
        <t-row class="content" justify="space-between">
          <t-col v-for="(item, index) in USER_INFO_LIST" :key="index" class="contract" :span="item.span || 3">
            <div class="contract-title">{{ item.title }}</div>
            <div class="contract-detail" v-show="!edit || item.title == '用户类型'"
              v-if="index == 1 && item.content == 'Doctor'">医生</div>
            <div class="contract-detail" v-show="!edit || item.title == '用户类型'"
              v-else-if="index == 1 && item.content == 'Manager'">管理员</div>
            <div class="contract-detail" v-show="!edit || item.title == '用户类型'" v-else>{{ item.content }}</div>
            <div class="contract-detail" v-show="edit && item.title != '用户类型'">
              <t-input v-model="edited[index]"></t-input>
            </div>
          </t-col>
        </t-row>
      </card>

      <card class="user-info-list" size="small" title="修改密码">
        <template #option>
          <t-button theme="default" shape="square" variant="text" @click="showChangePassword">
            <t-icon name="edit" size="18" />
          </t-button>
        </template>
        <t-row class="content" justify="space-between"></t-row>
      </card>
    </t-col>
    <t-dialog header="请验证密码" :visible.sync="showPassword" @confirm="confirmPassword()" mode="modeless"
      @cancel="cancelInfo">
      <t-form :data="checkPassword">
        <t-form-item label="密码:">
          <t-input v-model="checkPassword.password" placeholder="请输入现用的密码" type="password"></t-input>
        </t-form-item>
      </t-form>
    </t-dialog>
    <t-dialog header="请输入手机号" :visible.sync="showNoPhone" mode="modeless" :cancelBtn="null" :confirmBtn="null">
    </t-dialog>

    <t-dialog header="请输入新密码" :visible.sync="showNewPassword" @confirm="recheckPassword()" mode="modeless"
      @cancel="cancelInfo">
      <t-form :data="checkPassword">
        <t-form-item label="新密码:">
          <t-input v-model="checkPassword.password" placeholder="请输入新的密码" type="password"></t-input>
        </t-form-item>
        <t-form-item label="确认密码:">
          <t-input v-model="checkPassword.repassword" placeholder="请再次输入新的的密码" type="password"></t-input>
        </t-form-item>
      </t-form>
    </t-dialog>

    <t-dialog header="请验证新电话号码" :visible.sync="showPhone" @confirm="confirmPhone()" mode="modeless"
      @cancel="cancelInfo">
      <t-row>
        <t-col :span="7">
          <t-form :data="checkPassword">
            <t-form-item label="验证码:">
              <t-input v-model="checkPassword.password" placeholder="请输入验证码"></t-input>
            </t-form-item>
          </t-form>
        </t-col>
        <t-col :span="3">
          <t-button theme="primary" variant="text" @click="sendVeri" :disabled="veriDisable">{{ veriNotice }}</t-button>
        </t-col>
      </t-row>
    </t-dialog>
  </t-row>
</template>
<script>
  import {
    prefix
  } from '@/config/global';

  import {
    LAST_7_DAYS
  } from '@/utils/date.ts';
  import * as echarts from 'echarts/core';
  import {
    mapState
  } from 'vuex';

  import {
    GridComponent,
    TooltipComponent,
    LegendComponent
  } from 'echarts/components';
  import {
    LineChart
  } from 'echarts/charts';
  import {
    CanvasRenderer
  } from 'echarts/renderers';
  import {
    changeChartsTheme,
    getFolderLineDataSet
  } from '@/pages/dashboard/base/index';

  // import { USER_INFO_LIST, TEAM_MEMBERS, PRODUCT_LIST } from '@/service/service-user';
  import ProductAIcon from '@/assets/assets-product-1.svg';
  import ProductBIcon from '@/assets/assets-product-2.svg';
  import ProductCIcon from '@/assets/assets-product-3.svg';
  import ProductDIcon from '@/assets/assets-product-4.svg';

  import Card from '@/components/card/index.vue';

  // echarts.use([GridComponent, TooltipComponent, LineChart, CanvasRenderer, LegendComponent]);

  export default {
    name: 'UserIndex',

    components: {
      Card,
      ProductAIcon,
      ProductBIcon,
      ProductCIcon,
      ProductDIcon
    },
    data() {
      return {
        prefix,
        dashboardBase: '',
        lineContainer: '',
        lineChart: '',
        edit: false,
        changePassword: false,
        edited: [],
        showPassword: false,
        showNewPassword: false,
        showPhone: false,
        checkPassword: {},
        changePhone: false,
        veriNotice: '发送验证码',
        veriCode: '',
        exceed: '',
        veriDisable: false,
        veriTime: 60,
        interval: '',
        changeUserInfo: 0,
        showNoPhone: false
        // LAST_7_DAYS,
        // USER_INFO_LIST,
        // TEAM_MEMBERS,
        // PRODUCT_LIST
      };
    },
    computed: {
      ...mapState('setting', ['brandTheme', 'mode']),
      name() {
        return this.$store.state.user.userInfo.name;
      },
      USER_INFO_LIST: {
        get() {
          console.log('USERINFOLIST get');
          let result = [];
          let local = localStorage.getItem('info');
          if (local != '') {
            this.$store.commit('user/setUserInfo', JSON.parse(local));
          }
          for (let item in this.$store.state.user.userInfo) {
            switch (item) {
              case 'type': {
                result.push({
                  title: '用户类型',
                  content: this.$store.state.user.userInfo[item]
                });
                break;
              }
              case 'name': {
                result.push({
                  title: '姓名',
                  content: this.$store.state.user.userInfo[item]
                });
                break;
              }
              case 'phone': {
                result.push({
                  title: '电话',
                  content: this.$store.state.user.userInfo[item]
                });
                break;
              }
              case 'hospital': {
                result.push({
                  title: '医院',
                  content: this.$store.state.user.userInfo[item]
                });
                break;
              }
              case 'roles': {
                break;
              }
            }
          }

          // console.log(result)
          return result;
        },
        set() {
          console.log('USERINFOLIST set');
          let result = [];
          for (let item in this.$store.state.user.userInfo) {
            switch (item) {
              case 'type': {
                result.push({
                  title: '用户类型',
                  content: this.$store.state.user.userInfo[item]
                });
                break;
              }
              case 'name': {
                result.push({
                  title: '姓名',
                  content: this.$store.state.user.userInfo[item]
                });
                break;
              }
              case 'phone': {
                result.push({
                  title: '电话',
                  content: this.$store.state.user.userInfo[item]
                });
                break;
              }
              case 'hospital': {
                result.push({
                  title: '医院',
                  content: this.$store.state.user.userInfo[item]
                });
                break;
              }
              case 'roles': {
                break;
              }
            }
          }
          // console.log(result)
          return result;
        }
      }
    },
    watch: {
      // brandTheme() {
      //   changeChartsTheme([this.lineChart]);
      // },
      // mode() {
      //   this.renderCharts();
      // },
      // lineChart() {
      //   this.updateContainer();
      // }
    },
    mounted() {
      window.addEventListener('resize', this.updateContainer, false);
      // this.renderCharts();
      // this.$nextTick(() => {
      //   this.updateContainer();
      // });

      if (localStorage.getItem('ovcf-token') != undefined) {
        console.log('set token');
        this.$store.commit('user/setToken', localStorage.getItem('ovcf-token'));
        this.$store.commit('user/setUserInfo', JSON.parse(localStorage.getItem('info')));
      }
    },
    methods: {
      cancelInfo() {
        this.edit = false;
        this.edited = [];
        this.veriDisable = false;
        this.veriTime = 60;
        window.clearInterval(this.interval);
        this.veriNotice = '发送验证码';
        this.USER_INFO_LIST = this.USER_INFO_LIST;
        this.changePassword = false;
        this.showPassword = false;
        this.changePhone = false;
        this.showPhone = false;
        this.showNewPassword = false;
        this.checkPassword = {};
        this.showNoPhone = false;
      },
      noShowNoPhone() {
        this.showNoPhone = false;
      },
      showChangePassword() {
        this.changePassword = true;
        this.showPassword = true;
      },
      clickEdit() {
        this.edit = !this.edit;
        for (let i = 0; i < this.USER_INFO_LIST.length; i++) {
          this.edited.push(this.USER_INFO_LIST[i].content);
        }
      },
      async recheckPassword() {
        console.log('changePassword');
        if (this.checkPassword.password == this.checkPassword.repassword) {
          await this.$request
            .post('/doctor-info-modify?type=password', {
              info: this.checkPassword.password,
              phone: this.USER_INFO_LIST[3].content
            })
            .then(async res => {
              if (res.code === 0) {
                this.$message.success('修改成功！');
              } else {
                console.log(res.data);
                this.$message.error(res.data.info);
              }
            })
            .catch(e => {
              this.$message.error('修改提交失败！');
              console.log(e);
            })
            .finally(() => {
              this.cancelInfo();
            });
        }
      },
      //提交修改
      confrimEdit() {
        let post = [];
        if (this.edited[3] == '') {
          this.showNoPhone = true;
          return;
        }
        for (let i = 0; i < this.edited.length; i++) {
          switch (i) {
            case 3: {
              if (this.edited[i] != this.USER_INFO_LIST[i].content) {
                this.changePhone = true;
                post.push({
                  type: 'phone',
                  content: this.edited[i]
                });
              }
              break;
            }
            case 0: {
              if (this.edited[i] != this.USER_INFO_LIST[i].content) {
                post.push({
                  type: 'name',
                  content: this.edited[i]
                });
              }
              break;
            }
            case 2: {
              if (this.edited[i] != this.USER_INFO_LIST[i].content) {
                post.push({
                  type: 'phone',
                  content: this.edited[i]
                });
              }
              break;
            }
          }
        }
        if (post.length == 0) {
          this.cancelInfo();
          return;
        }
        this.showPassword = true;
        console.log(this.changePhone, post);
      },
      //确认密码
      async confirmPassword() {
        await this.$request
          .post('/doctor-login?type=password', {
            phone: this.USER_INFO_LIST[3].content,
            password: this.checkPassword.password
          })
          .then(async res => {
            console.log(res);
            this.$store.commit('user/setToken', res.token);
            this.$store.commit('user/setUserInfo', res.info);
            if (res.code === 0 && this.edit == true) {
              console.log(res);
              this.showPassword = false;
              this.checkPassword.password = '';
              if (this.changePhone == true) {
                this.showPhone = true;
              } else {
                await this.$request
                  .post('/doctor-info-modify?type=info', {
                    info: this.edited,
                    phone: this.USER_INFO_LIST[3].content
                  })
                  .then(async res => {
                    if (res.code === 0) {
                      this.$store.commit('user/setUserInfo', {
                        name: this.edited[0],
                        type: this.edited[1],
                        hospital: this.edited[2],
                        phone: this.edited[3]
                      });
                      if (localStorage.getItem("info") != "") {
                        localStorage.setItem("info", JSON.stringify({
                          name: this.edited[0],
                          type: this.edited[1],
                          hospital: this.edited[2],
                          phone: this.edited[3]
                        }))
                      }
                      this.$message.success('修改成功！');
                    } else {
                      console.log(res);
                      this.$message.error(res.data.info);
                    }
                  })
                  .catch(e => {
                    this.$message.error('修改提交失败！');
                    console.log(e);
                  })
                  .finally(() => {
                    this.cancelInfo();
                  });
              }
            } else if (res.code === 0 && this.changePassword == true) {
              this.showPassword = false;
              this.showNewPassword = true;
              this.checkPassword = {};
            } else {
              this.$message.error('密码错误！请检查密码');
            }
          })
          .catch(e => {
            console.log(e);
          })
          .finally(() => {});
      },
      //确认手机验证码
      async confirmPhone() {
        console.log(this.checkPassword, this.veriCode, new Date().getTime() < this.exceed);
        if (this.checkPassword.password == this.veriCode && new Date().getTime() < this.exceed) {
          this.$message.success('验证成功！');
          await this.$request
            .post('/doctor-info-modify?type=info', {
              info: this.edited,
              phone: this.USER_INFO_LIST[3].content
            })
            .then(async res => {
              if (res.code === 0) {
                this.$store.commit('user/setUserInfo', {
                  name: this.edited[0],
                  type: this.edited[1],
                  hospital: this.edited[2],
                  phone: this.edited[3]
                });
                this.$message.success('修改成功！');
                if (localStorage.getItem("info") != "") {
                  localStorage.setItem("info", JSON.stringify({
                    name: this.edited[0],
                    type: this.edited[1],
                    hospital: this.edited[2],
                    phone: this.edited[3]
                  }))
                }
              } else {
                console.log(res);
                this.$message.error(res.data.info);
              }
              this.cancelInfo();
            })
            .catch(e => {
              this.$message.error('修改提交失败！');
              console.log(e);
            })
            .finally(() => {});
        } else {
          this.$message.error('验证码错误或已过期！');
        }
      },
      //发送验证码
      async sendVeri() {
        await this.$request
          .post('/send-verify?phone=' + this.edited[3])
          .then(async res => {
            console.log(res);
            if (res.code === 0) {
              this.$message.success('验证码已发送！有效期一小时');
              this.veriCode = res.veriCode;
              this.exceed = new Date(new Date().getTime() + 1 * 60 * 60 * 1000).getTime();
              let me = this;
              me.veriDisable = true;
              this.interval = window.setInterval(function() {
                me.veriNotice = '已发送 ' + me.veriTime;
                me.veriTime--;
                if (me.veriTime < 0) {
                  me.veriNotice = '发送验证码';
                  me.veriDisable = true;
                  me.veriTime = 60;
                  window.clearInterval(interval);
                }
              }, 1000);
            } else {
              this.$message.error('发送验证码失败！请稍后再试');
            }
          })
          .catch(e => {
            // this.exceed = new Date(new Date().getTime() + 1 * 60 * 60 * 1000);
            // let me = this;
            // me.veriDisable = true;
            // this.interval = window.setInterval(function() {
            //   me.veriNotice = '已发送 ' + me.veriTime;
            //   me.veriTime--;
            //   if (me.veriTime < 0) {
            //     me.veriNotice = '发送验证码';
            //     me.veriDisable = true;
            //     me.veriTime = 60;
            //     window.clearInterval(interval);
            //   }
            // }, 1000);
            this.$message.error('发送验证码失败！请稍后再试');
            console.log(e);
          })
          .finally(() => {});
      }
    }
  };
</script>
<style lang="less" scoped>
  @import url('./index.less');
</style>
